package thu.cs.segroup.agent.behaviour;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import thu.cs.segroup.agent.Coordinator;
import thu.cs.segroup.entity.TestCase;
import thu.cs.segroup.entity.TestTask;
import thu.cs.segroup.util.Constants;

import jade.core.Agent;
import jade.core.behaviours.OneShotBehaviour;
import jade.core.behaviours.SequentialBehaviour;
import jade.lang.acl.ACLMessage;

public class CoorAllocateTaskBehav extends OneShotBehaviour {

	public CoorAllocateTaskBehav(Agent agent) {
		super(agent);
	}
	
	@Override
	public void action() {
		Coordinator coor = (Coordinator)myAgent;
		HashMap<String, LinkedList> selected_runner = (HashMap<String, LinkedList>)coor.getProperty(Constants.COOR_SELECTED_RUNNER_SET);
		List<TestCase> tc_list = (List<TestCase>)coor.getProperty(Constants.COOR_CURRENT_TC_SET);
		HashMap<String, String> deploy_map = new HashMap<String, String>();
		
		ArrayList<TestTask> total_task = new ArrayList<TestTask>();
		ArrayList<String> runner_seqence = new ArrayList<String>();
		
		// System.out.println(tc_list.size());
		
		for (int i = 0; i < tc_list.size(); i++) {
			List<TestTask> task_list = tc_list.get(i).getTaskList();
			for (int j = 0; j < task_list.size(); j++) {
				LinkedList<String> str_lst = selected_runner.get(tc_list.get(i).getId());
				if (str_lst == null) {
					System.out.println("NULL");
				}
				String runner_name = str_lst.pollFirst();
				deploy_map.put(runner_name, tc_list.get(i).getConfigs().get(j).getHost());
				task_list.get(j).setName(tc_list.get(i).getId() + "_" + runner_name);
				total_task.add(task_list.get(j));
				runner_seqence.add(runner_name);
			}
			// added
			if (selected_runner.get(tc_list.get(i).getId()).size() == 0) {
				selected_runner.remove(tc_list.get(i).getId());
			}
		}
		
		coor.addProperty(Constants.COOR_RUNNER_DEPLOY_MAP, deploy_map);
		SequentialBehaviour sb = new SequentialBehaviour(myAgent);
		for (int i = 0; i < runner_seqence.size(); i++) {
			ArrayList<String> des = new ArrayList<String>();
			des.add(runner_seqence.get(i));
			TestTask task = total_task.get(i);
			// System.out.println("AllocateTask LOG: Task " + task.getName() + " is allocated to " + runner_seqence.get(i));
			sb.addSubBehaviour(new CommonSendObjMsgBehav(total_task.get(i), des, Constants.TASK_ARRIVE, ACLMessage.INFORM,
					myAgent));
		}
		myAgent.addBehaviour(sb);		
		
	}

}
